package com.itsu.shirojwt.utils;

import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import org.springframework.util.StringUtils;

public class JWTUtil {
    // 过期时间5分钟
    private static final long EXPIRE_TIME = 5 * 60 * 1000;

    /**
     * 生成签名,5min后过期
     *
     * @param username 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(final String username, final String secret) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(secret)) {
            throw new IllegalArgumentException("username or secret is null or empty");
        }
        final String token = JWT.create().withAudience(username)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME)).sign(Algorithm.HMAC256(secret));
        return token;
    }

    public static boolean verify(final String token, final String secret) {
        try {
            final JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            verifier.verify(token);
            return true;
        } catch (final Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static DecodedJWT decode(final String token) throws Exception {
        if (StringUtils.isEmpty(token)) {
            throw new IllegalArgumentException("token is null or empty");
        }
        return JWT.decode(token);
    }

    public static Date getExpireTime(final String token) throws Exception {
        final DecodedJWT decodeJwt = decode(token);
        return decodeJwt.getExpiresAt();
    }

    public static String getUserName(final String token) throws Exception {
        return decode(token).getAudience().get(0);
    }

}